<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="goodsId">
        <el-select
          v-model="queryParams.goodsId"
          placeholder="请选择商品名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        >
          <el-option
            v-for="goodsInfo in goodsInfoList"
            :key="goodsInfo.id"
            :label="goodsInfo.goodsName"
            :value="goodsInfo.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="销售日期" prop="salesTime">
        <el-date-picker clearable
          v-model="queryParams.salesTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择销售日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="销售员" prop="userId">
        <el-select
          v-model="queryParams.userId"
          placeholder="请选择销售名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        >
          <el-option
            v-for="user in userlist"
            :key="user.userId"
            :label="user.nickName"
            :value="user.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['goods:goodsSalesInfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['goods:goodsSalesInfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['goods:goodsSalesInfo:remove']"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['goods:goodsSalesInfo:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsSalesInfoList" @selection-change="handleSelectionChange" show-summary :summary-method="getSummaries">
      <el-table-column type="selection" width="80" align="center" />
      <el-table-column type="index" label="序号" align="center"></el-table-column>
      <el-table-column label="商品名称" align="center" prop="goodsName"/>
      <el-table-column prop="unit" label="单位"  align="center" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.unit" :value="scope.row.unit"/>
        </template>
      </el-table-column>
      <el-table-column label="销售日期" align="center" prop="salesTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.salesTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="userType" label="销售类型"  align="center" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.user_type" :value="scope.row.userType"/>
        </template>
      </el-table-column>
      <el-table-column label="销售员" align="center" prop="userId">
        <template slot-scope="scope">
          {{
            selectUserDictLabel(
              'userId',
              'nickName',
              scope.row.userId
            )
          }}
        </template>
      </el-table-column>
      <el-table-column label="销售总额" align="center" prop="salesTotal" />
      <el-table-column label="销售数量" align="center" prop="salesNum" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新人名称" align="center">
        <template slot-scope="scope">
          {{
            selectUserDictLabel(
              'userId',
              'nickName',
              scope.row.updateBy
            )
          }}
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改仓库销售流水对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="goodsId">
          <el-select
            v-model="form.goodsId"
            placeholder="请选择商品名称"
            clearable
          >
            <el-option
              v-for="goodsInfo in goodsInfoList"
              :key="goodsInfo.id"
              :label="goodsInfo.goodsName"
              :value="goodsInfo.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="销售日期" prop="salesTime">
          <el-date-picker clearable
            v-model="form.salesTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择销售日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="销售类型" prop="userType">
          <el-radio-group v-model="form.userType">
            <el-radio
              v-for="dict in dict.type.user_type"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="销售员" prop="userId">
          <el-select
            v-model="form.userId"
            placeholder="请选择销售员"
            clearable
            :disabled="disable"
          >
            <el-option
              v-for="user in userlist"
              :key="user.userId"
              :label="user.nickName"
              :value="user.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="销售总额" prop="salesTotal">
          <el-input-number v-model="form.salesTotal" placeholder="请输入销售总额" :precision="2"  ></el-input-number> 元
        </el-form-item>
        <el-form-item label="销售数量" prop="salesNum">
          <el-input-number v-model="form.salesNum" placeholder="请输入销售数量" :precision="2"></el-input-number>
        </el-form-item>
        <el-form-item label="零售价" prop="retailPrice">
          <el-input v-model="form.retailPrice" placeholder="请输入零售价"  :readonly="true"/>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listGoodsSalesInfo, getGoodsSalesInfo, delGoodsSalesInfo, addGoodsSalesInfo, updateGoodsSalesInfo } from "@/api/goods/goodsSalesInfo";
import { listAll } from '@/api/goods/goodsInfo'

export default {
  name: "GoodsSalesInfo",
  dicts: ['user_type','unit'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 仓库销售流水表格数据
      goodsSalesInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsId: null,
        salesTime: null,
        salesTotal: null,
        userId: null,
        userName: null,
        userType: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        goodsId: [
          { required: true, message: "商品名称不能为空", trigger: "change" }
        ],
        salesTime: [
          { required: true, message: "销售日期不能为空", trigger: "change" }
        ],
        userType: [
          { required: true, message: "销售类型不能为空", trigger: "blur" }
        ],
        salesTotal: [
          { required: true, message: "销售总额不能为空", trigger: "blur" }
        ],
        userId: [
          { required: true, message: "销售员不能为空", trigger: "change" }
        ],
      },
      goodsInfoList:[],
      userlist:[],
      user:{},
      disable:true
    };
  },
  created() {
    this.getGoodsInfoList();
    this.getList();
    if(this.$auth.hasRole("system") || this.$auth.hasRole("admin"))
    {
      this.disable = false;
    }

    this.userlist = this.$store.getters.users
    let temp = JSON.stringify(this.$store.getters.users.find(i => i.userName === this.$store.getters.name))
    this.user = JSON.parse(temp)
  },

  watch:{
    'form.salesTotal'(newval,oldval) {
      if(parseInt(this.form.salesNum)>0)
      {
        this.form.retailPrice =  parseFloat(this.form.salesTotal/this.form.salesNum).toFixed(2);
      }else{
        this.form.retailPrice = 0
      }
    },
    'form.salesNum'(newval,oldval) {
      if(parseInt(this.form.salesNum)>0)
      {
        this.form.retailPrice =  parseFloat(this.form.salesTotal/this.form.salesNum).toFixed(2);
      }else{
        this.form.retailPrice = 0
      }
    }
  },
  methods: {
    /** 查询仓库销售流水列表 */
    getList() {
      this.loading = true;
      listGoodsSalesInfo(this.queryParams).then(response => {
        this.goodsSalesInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getGoodsInfoList()
    {
      listAll().then(response => {
        this.goodsInfoList = response.rows;
        if(this.goodsInfoList)
        {
            this.goodsInfoList.forEach(e=>{
            e.goodsName = e.goodsName+"（"+this.selectDictLabel(this.dict.type.unit, e.unit)+"）"
            })
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        goodsId: null,
        salesTime: null,
        salesTotal: null,
        userId: null,
        userName: null,
        userType: 0,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.form.userId = this.user.userId
      this.title = "添加仓库销售流水";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getGoodsSalesInfo(id).then(response => {
        this.form = response.data;
        this.form.userId = response.data.userId+""
        this.form.userType = response.data.userType+""
        this.open = true;
        this.title = "修改仓库销售流水";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateGoodsSalesInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoodsSalesInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除仓库销售流水编号为"' + ids + '"的数据项？').then(function() {
        return delGoodsSalesInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('goods/goodsSalesInfo/export', {
        ...this.queryParams
      }, `goodsSalesInfo_${new Date().getTime()}.xlsx`)
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = {};
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (column.label === "销售总额" || column.label === "销售数量") {
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            // sums[index] += ' kg';
          } else {
            // sums[index] = 'N/A';
          }
        }
      });
      return sums;
    },
  }
};
</script>
